package com.jdy.haoduoai.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.adapter.BabyKalaokAdapter;
import com.jdy.haoduoai.enums.SelectionMode;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.BabyKalaokItem;
import com.jdy.haoduoai.model.BabyKalaokItemWrapper;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout;
import com.jdy.haoduoai.pulltorefresh.PullToRefreshLayout.OnRefreshListener;
import com.jdy.haoduoai.pulltorefresh.PullableListView;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.RippleView;
import com.jdy.haoduoai.view.RippleView.OnRippleCompleteListener;
import com.jdy.haoduoai.widget.CustomCommonDialog;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

//import com.jdy.haoduoai.R;

@SuppressLint("HandlerLeak")
public class BabyKaraokeActivity extends BaseActivity implements
    OnClickListener {

  @InjectView(id = R.id.content_views)
  private PullableListView listview;
  @InjectView(id = R.id.refresh_view)
  private PullToRefreshLayout pullToRefreshLayout;
  @InjectView(id = R.id.emptylayout)
  private LinearLayout emptylayout;
  @InjectView(id = R.id.reloadRippleView)
  private RippleView reloadRippleView;
  @InjectView(id = R.id.bottomlyt)
  private LinearLayout bottomlyt;
  @InjectView(id = R.id.delete, click = true)
  private Button delete;
  @InjectView(id = R.id.select, click = true)
  private Button select;

  private BabyKalaokAdapter adapter;
  private LeUser mLeUser;
  public boolean isLogin;
  public boolean isrefreshlist = false;
  public String SNO;
  private ArrayList<BabyKalaokItem> mAdapterList = null;
  private ArrayList<BabyKalaokItem> mArrayList = null;
  private int mLastPage = 1;

  @Override
  @SuppressLint("InflateParams")
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().setFormat(PixelFormat.TRANSLUCENT);
    setContentView(R.layout.activity_kalaok);
    setTitle("宝宝唱的卡拉OK");
    // getbtn_right().setVisibility(View.VISIBLE);
    // getbtn_right().setBackgroundResource(R.drawable.edit_btn);
    // getbtn_right().setOnClickListener(new OnClickListener() {
    // @Override
    // public void onClick(View v) {
    // if (bottomlyt.isShown()) {
    // bottomlyt.setVisibility(View.GONE);
    // adapter.setEditor(false);
    // adapter.notifyDataSetChanged();
    // getbtn_right().setBackgroundResource(R.drawable.edit_btn);
    // } else {
    // bottomlyt.setVisibility(View.VISIBLE);
    // adapter.setEditor(true);
    // adapter.notifyDataSetChanged();
    // getbtn_right().setBackgroundResource(R.drawable.cancle);
    // }
    // }
    // });
    initialize();
    initHandler();
    initListener();
    requestData();
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (handler != null) {
      handler.removeCallbacksAndMessages(null);
      handler = null;
    }
  }

  private void requestData() {
    loadDataAsync(true);
  }

  private void initialize() {
    mArrayList = new ArrayList<BabyKalaokItem>();
    mAdapterList = new ArrayList<BabyKalaokItem>();
    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    isLogin = LeConfig.isLogin;

    if (Tools.isEmpty(mLeUser)) {
      mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    }

    SNO = mLeUser.sno;

    listview.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
          long arg3) {
        Intent intent = new Intent(BabyKaraokeActivity.this,
            BabyTellStoryDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("rank_map", adapter.getList().get(arg2));
        intent.putExtras(bundle);
        startActivity(intent);
      }
    });
  }

  private void initHandler() {
    handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
        super.handleMessage(msg);

        dismissLoading();

        if (isrefreshlist) {
          mArrayList.clear();
        }

        if (mAdapterList != null && !mAdapterList.isEmpty()) {
          mArrayList.addAll(mAdapterList);
          setAdapter();
        }

        if (mArrayList != null
            && mArrayList.size() == mBabyKalaokItemWrapper.total) {
          pullToRefreshLayout.refreshFinish(PullToRefreshLayout.LOAD_COMPLETED);
          pullToRefreshLayout
              .loadmoreFinish(PullToRefreshLayout.LOAD_COMPLETED);
        } else {
          pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
          pullToRefreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
        }
      }
    };
  }

  private void setAdapter() {
    if (adapter == null) {
      adapter = new BabyKalaokAdapter(this, mArrayList, SNO);
      listview.setAdapter(adapter);
    } else {
      adapter.notifyDataSetChanged();
    }
    if (adapter.getCount() == 0) {
      emptylayout.setVisibility(View.VISIBLE);
    } else {
      emptylayout.setVisibility(View.GONE);
    }
  }

  private void initListener() {
    reloadRippleView
        .setOnRippleCompleteListener(new OnRippleCompleteListener() {
          @Override
          public void onComplete(RippleView rippleView) {
            isrefreshlist = true;
            loadDataAsync(true);
          }
        });

    pullToRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
      @Override
      public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        mLastPage = 1;
        isrefreshlist = true;
        loadDataAsync(false);
      }

      @Override
      public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        mLastPage++;
        isrefreshlist = false;
        loadDataAsync(false);
      }
    });
  }

  private BabyKalaokItemWrapper mBabyKalaokItemWrapper;

  private void loadDataAsync(boolean isShow) {
    if (mAdapterList != null && !mAdapterList.isEmpty()) {
      mAdapterList.clear();
    }

    if (isShow) {
      showloading("");
    }

    Async.start(new Func0<ResponseResult>() {
      @Override
      public ResponseResult call() {
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);

        LeMachine lm = LeXiaoXiaoBanApp.getInstance().getBaby();
        if (lm != null) {
          param_.put("member_id", lm.id);
        }

        param_.put("catalog", "kalaok");
        param_.put("page", mLastPage);

        return HttpUtils.startRequest(
            HttpUtils.API_URL + "/api/2.0/member/dub", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).filter(new Func1<ResponseResult, Boolean>() {
      @Override
      public Boolean call(ResponseResult arg0) {
        return arg0 != null && Tools.isNotEmpty(arg0) && arg0.isSuccess();
      }
    }).doOnCompleted(new Action0() {
      @Override
      public void call() {
        Message message = new Message();
        message.what = mLastPage;
        if (handler != null) {
          handler.sendMessage(message);
        }
        // mLastPage++;
      }
    }).subscribe(new Action1<ResponseResult>() {
      @Override
      public void call(ResponseResult arg0) {
        mBabyKalaokItemWrapper = JsonSerializer.getInstance().deserialize(
            arg0.data, BabyKalaokItemWrapper.class);

        mAdapterList.addAll(mBabyKalaokItemWrapper.data);
      }
    });

  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.delete:
      int selectCount = 0;

      if (mArrayList != null) {
        for (BabyKalaokItem item : mArrayList) {
          if (item != null && item.isChecked) {
            ++selectCount;
          }
        }
      }

      if (selectCount > 0) {
        CustomCommonDialog.Builder cdb = new CustomCommonDialog.Builder(
            BabyKaraokeActivity.this).setMessage("确定删除吗？").setTitle("删除提示")
            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
              }
            }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
              @Override
              public void onClick(DialogInterface dialog, int id) {

                if (mArrayList != null && !mArrayList.isEmpty()) {
                  final List<BabyKalaokItem> selectedRecordings = new ArrayList<BabyKalaokItem>();
                  String storyIds = "";

                  for (BabyKalaokItem item : mArrayList) {
                    if (item.isChecked) {
                      selectedRecordings.add(item);
                      storyIds += item.id;
                      storyIds += ";";
                    }
                  }

                  if (Tools.isNotEmpty(storyIds)) {
                    storyIds = storyIds.substring(0, storyIds.length() - 1);
                  }

                  if (selectedRecordings.size() > 0) {
                    final String finalStoryIds = storyIds;
                    new CustomAsyncTask(BabyKaraokeActivity.this,
                        new IAsyncTask() {
                          @Override
                          public void onRecieveData(Activity activity,
                              ResponseResult result) {

                            // if (result != null && result.isSuccess()) {
                            for (BabyKalaokItem rItem : selectedRecordings) {
                              adapter.remove(rItem);
                            }
                            adapter.removeSelection();

                            if (Tools.isNotNullStr(result.data)) {
                              Toast.makeText(BabyKaraokeActivity.this,
                                  result.data, Toast.LENGTH_SHORT).show();
                            }
                            // }
                          }

                          @Override
                          public ResponseResult doInbackground(Activity activity) {
                            if (mLeUser == null) {
                              mLeUser = Tools.restoreLeUser();
                            }

                            HashMap<String, Object> param_ = new HashMap<String, Object>();
                            param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
                            param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
                            return HttpUtils.startRequest(HttpUtils.HOST_API
                                + "/api/2.0/member/dub/" + finalStoryIds,
                                param_, HttpUtils.TAG_DELETE_REQUEST);
                          }
                        }).execute();

                  }
                  dialog.dismiss();
                }
              }
            });
        cdb.create().show();
      } else {
        toastShow("未选中任何条目!");
      }
      break;
    case R.id.select:
      if (select.getText().toString().equals("全选")) {
        adapter.setSelectMode(SelectionMode.SELECT_ALL);
        adapter.notifyDataSetChanged();
        select.setText("取消全选");
      } else if (select.getText().toString().equals("取消全选")) {
        adapter.setSelectMode(SelectionMode.DESELECT_ALL);
        adapter.notifyDataSetChanged();
        select.setText("全选");
      }
      break;
    default:
      break;
    }

  }
}
